﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace RegexLib.Web.Models.Web
{
	/// <summary>
	/// 为需要分级显示的东西提供支持。
	/// </summary>
	public class RxRank
	{
		/// <summary>
		/// 根据rank得到rank的level。（该加强中文水平了！什么名字中文表达不了的非要用英文……）
		/// </summary>
		/// <param name="allRanks">所有可能的rank。</param>
		/// <param name="rank">要获取对应level的rank。此数组中的每个值应该唯一。</param>
		/// <param name="minLevel">level可能的最大值。</param>
		/// <param name="maxLevel">level可能的最小值。</param>
		/// <returns>与rank对应的level。</returns>
		public static int GetLevel(int[] allRanks, int rank, int minLevel, int maxLevel)
		{
			int base1maxLevel = maxLevel - minLevel + 1;
			int[] sortedUniqueRanks = allRanks.Distinct().OrderBy(r => r).ToArray();

			if (!sortedUniqueRanks.Contains(rank))
				throw new ArgumentException("The given rank is not contained in all possible rank values.", "rank");

			// Calculate the place of rank value.
			int place = 0;
			while (place < sortedUniqueRanks.Length && sortedUniqueRanks[place] != rank)
				place++;

			if (base1maxLevel <= sortedUniqueRanks.Length)
				return (place + 1) * base1maxLevel / sortedUniqueRanks.Length;
			else
				return (place + 1) * base1maxLevel / (sortedUniqueRanks.Length + 1);
		}

		/// <summary>
		/// 根据rank得到rank的level（假定level最小值为1）。
		/// </summary>
		/// <param name="allRanks">所有可能的rank。</param>
		/// <param name="rank">要获取对应level的rank。</param>
		/// <param name="maxLevel">level可能的最小值。</param>
		/// <returns>与rank对应的level。</returns>
		public static int GetLevel(int[] allRanks, int rank, int maxLevel)
		{
			return GetLevel(allRanks, rank, 1, maxLevel);
		}

		/// <summary>
		/// 根据rank得到rank的level（假定level最小值为1，最大值为10）。
		/// </summary>
		/// <param name="allRanks">所有可能的rank。</param>
		/// <param name="rank">要获取对应level的rank。</param>
		/// <returns>与rank对应的level。</returns>
		public static int GetLevel(int[] allRanks, int rank)
		{
			return GetLevel(allRanks, rank, 1, 10);
		}
	}
}
